﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using UFIDA.U9.Base.FlexField.DescFlexField;
using UFIDA.U9.Base.UOM;
using UFIDA.U9.CBO.Pub.Controller;
using UFIDA.U9.CBO.Pub.Controller.Proxy;
using UFIDA.U9.CBO.SCM.Item;
using UFIDA.U9.CBO.SCM.Supplier;
using UFIDA.U9.Cust.YYD.WebApi.Dtos;
using UFIDA.U9.Cust.YYD.WebApi.Dtos.RequestDtos;
using UFIDA.U9.Cust.YYD.WebApi.Dtos.ReturnDtos;
using UFIDA.U9.Cust.YYD.WebApi.Public;
using UFIDA.UBF.SystemManage;
using UFIDA.UBF.SystemManage.Agent;
using UFSoft.UBF.AopFrame.Lock;
using UFSoft.UBF.Business;
using UFSoft.UBF.MVC;
using UFSoft.UBF.Transactions;
using UFSoft.UBF.Util.DataAccess;

namespace UFIDA.U9.Cust.YYD.WebApi.Controllers
{
    public class PLMController : ApiController
    {
        [HttpPost]
        public ResultDto<string> CreateItemMaster(RequestPara<List<PLMItemPara>> paras)
        {
            using (BPForEngine bp1 = new BPForEngine())
            {
                PublicMethod.WriteContext(paras.Context, JsonConvert.SerializeObject(paras), this.GetType().Name);

                var data = paras.Data;
                ResultDto<string> rtn = new ResultDto<string>();
                //接口逻辑
                using (UBFTransactionScope scope = new UBFTransactionScope(TransactionOption.RequiresNew))
                {

                    List<XFDTO> xFDTOs = new List<XFDTO>();
                    UFIDA.U9.ISV.Item.BatchCreateItemByDTOSRV proxy = new UFIDA.U9.ISV.Item.BatchCreateItemByDTOSRV();
                    List<UFIDA.U9.ISV.Item.ItemMasterDTO> itemList = new List<UFIDA.U9.ISV.Item.ItemMasterDTO>();
                    try
                    {
                        string errmsg = string.Empty;
                        foreach (var item in paras.Data)
                        {
                            XFDTO xFDTO = new XFDTO();
                            xFDTO.OrgCode = item.Org;
                            xFDTO.ItemCode = item.Code;
                            xFDTO.ItemCode1 = item.Name;
                            xFDTOs.Add(xFDTO);

                            CBO.SCM.Item.ItemMaster itemMaster = CBO.SCM.Item.ItemMaster.Finder.Find("Code='" + item.Code + "' and Org.Code='10'");
                            if (itemMaster == null)
                            {
                                string msg = $"料品{item.Name}创建失败。";
                                UFIDA.U9.ISV.Item.ItemMasterDTO itemInfo = new UFIDA.U9.ISV.Item.ItemMasterDTO();
                                itemInfo.Org = new CBO.Pub.Controller.CommonArchiveDataDTO { Code = "10" };

                                CommonArchiveDataDTO uom = new CommonArchiveDataDTO();
                                if (!string.IsNullOrEmpty(item.UOM.ToString()))
                                {
                                    UOM uOM = UOM.Finder.Find("Name='" + item.UOM + "'");
                                    if (uOM != null)
                                        uom.Code = uOM.Code;
                                    else
                                    {
                                        msg += "单位" + item.UOM + "在ERP中不存在;";
                                    }
                                }
                                else
                                {
                                    msg += "单位参数为空;";
                                }

                                if (!string.IsNullOrEmpty(item.Code))
                                    itemInfo.Code = item.Code;
                                else
                                {
                                    msg += "编码参数为空;";
                                }
                                if (!string.IsNullOrEmpty(item.SPECS))
                                    itemInfo.Name = item.SPECS;
                                else
                                {
                                    msg += "品名参数为空;";
                                }

                                if (msg != "")
                                {
                                    errmsg += msg;
                                    continue;
                                }


                                itemInfo.Name = item.Name;
                                itemInfo.Code1 = item.Code1;
                                itemInfo.Code2 = item.Code2;
                                itemInfo.SPECS = item.SPECS;
                                itemInfo.IsBuildEnable = true;

                                switch (item.ItemFormAttribute.ToString())
                                {
                                    case "自制件":
                                        itemInfo.ItemFormAttribute = ItemTypeAttributeEnum.MakePart;//制造件
                                        break;
                                    case "外购件":
                                        itemInfo.ItemFormAttribute = ItemTypeAttributeEnum.PurchasePart;//采购件
                                        itemInfo.IsBuildEnable = false;
                                        break;
                                    case "外协件":
                                        itemInfo.ItemFormAttribute = ItemTypeAttributeEnum.SubcontractPart;//委外件
                                        break;
                                    case "虚拟":
                                        itemInfo.ItemFormAttribute = ItemTypeAttributeEnum.Phantom;//虚拟件
                                        continue;
                                    default:
                                        itemInfo.ItemFormAttribute = ItemTypeAttributeEnum.MakePart;//制造件
                                        break;
                                }
                                itemInfo.IsInventoryEnable = true;
                                itemInfo.IsPurchaseEnable = true;
                                itemInfo.IsSalesEnable = true;

                                itemInfo.IsOutsideOperationEnable = true;
                                itemInfo.IsMRPEnable = true;
                                itemInfo.IsBOMEnable = true;
                                itemInfo.IsVMIEnable = true;
                                itemInfo.InventoryUOM = uom;
                                itemInfo.InventorySecondUOM = uom;
                                itemInfo.SalesUOM = uom;
                                itemInfo.PurchaseUOM = uom;

                                itemInfo.PriceUOM = uom;
                                itemInfo.ManufactureUOM = uom;
                                itemInfo.MaterialOutUOM = uom;
                                itemInfo.CostUOM = uom;
                                itemInfo.ConverRatioRule = ConverRatioRuleEnum.Standard;//标准转换率
                                UFIDA.U9.ISV.Item.ItemInvInfoDTO m_invInfo = new UFIDA.U9.ISV.Item.ItemInvInfoDTO();

                                m_invInfo.InventoryPlanningMethod = InventoryPlanningMethodEnum.UseMRP;// MRP规划
                                m_invInfo.PurchaseControlMode = InvQtyCtlTypeEnum.MaxStockLimit;//最高存量限制

                                itemInfo.InventoryInfo = m_invInfo;

                                //料品采购信息DTO ItemPurchaseInfoDTO
                                UFIDA.U9.ISV.Item.ItemPurchaseInfoDTO m_purchaseInfo = new UFIDA.U9.ISV.Item.ItemPurchaseInfoDTO();
                                m_purchaseInfo.QuotaSupplier = QuotaSupplierEnum.VolumePurchase;//仅大批量采购
                                m_purchaseInfo.ReceiptType = ReceiptTypeEnum.ReceiptToWarehouse;//收货至仓库
                                m_purchaseInfo.PurchaseQuotaMode = PurchaseQuotaModeEnum.FixedRatioDistribute;//配额方式
                                m_purchaseInfo.ReceiptMode = ReceiptModeEnum.ArriveConfirm;//收货程序
                                CommonArchiveDataDTO receiptRule = new CommonArchiveDataDTO();//收货原则
                                receiptRule.Code = "10";
                                m_purchaseInfo.ReceiptRule = receiptRule;
                                itemInfo.PurchaseInfo = m_purchaseInfo;

                                //料品销售信息DTO ItemSaleInfoDTO
                                UFIDA.U9.ISV.Item.ItemSaleInfoDTO m_saleInfo = new UFIDA.U9.ISV.Item.ItemSaleInfoDTO();
                                m_saleInfo.LimitPriceMode = LimitPriceModeEnum.Absolute;//定义绝对价格
                                m_saleInfo.SupplySource = SupplySourceEnum.CurrentOrg;//当前组织
                                itemInfo.SaleInfo = m_saleInfo;

                                //料品生产信息DTO ItemMFGInfoDTO
                                UFIDA.U9.ISV.Item.ItemMFGInfoDTO m_mfgInfo = new UFIDA.U9.ISV.Item.ItemMFGInfoDTO();
                                m_mfgInfo.BuildShrinkageRate = 1M;//产出率
                                m_mfgInfo.IsSueOverType = null;// IsSueOverTypeEnum.Rate;//备料超额类型：0 比例 1 数量
                                m_mfgInfo.BuildQuanSelectType = BuildQuanSelectTypeEnum.AccordingRequestNum;//依需求量
                                m_mfgInfo.IsECNControl = true;
                                itemInfo.MfgInfo = m_mfgInfo;

                                //料品MRP（计划）信息DTO ItemMRPInfoDTO
                                UFIDA.U9.ISV.Item.ItemMRPInfoDTO m_mrpInfo = new UFIDA.U9.ISV.Item.ItemMRPInfoDTO();
                                m_mrpInfo.ForecastContorlType = ForecastContorlTypeEnum.ConsumeAndExport;//无
                                m_mrpInfo.MRPPlanningType = MRPPlanningMethodEnum.MRP;//MPS
                                m_mrpInfo.PlanningTimeFenceRuleType = PlanningTimeFenceRuleEnum.CustomerOrderPrimary;//客户订单
                                m_mrpInfo.PlanningTimeFence = PlanningTimeFenceTypeEnum.ItemSumTime;//累计汇总提前期
                                m_mrpInfo.DemandTimeFenceRuleType = DemandTimeFenceRuleEnum.CustomerOrderPrimary;//客户订单
                                m_mrpInfo.DemandTimeFence = DemandTimeFenceTypeEnum.ItemSumTime;//累计汇总提前期
                                m_mrpInfo.ReleaseTimeFence = ReleaseTimeFenceTypeEnum.ItemSumTime;//累计汇总提前期
                                itemInfo.MrpInfo = m_mrpInfo;

                                CommonArchiveDataDTO costCurrency = new CommonArchiveDataDTO();
                                costCurrency.Code = "C001";
                                itemInfo.CostCurrency = costCurrency;


                                //有效性
                                UFIDA.U9.Base.PropertyTypes.Effective effective = new UFIDA.U9.Base.PropertyTypes.Effective();
                                effective.EffectiveDate = DateTime.Parse("2000-01-01 00:00:00");
                                effective.DisableDate = DateTime.Parse("9999-12-31 00:00:00");
                                effective.IsEffective = true;
                                itemInfo.Effective = effective;
                                //itemInfo.DescFlexField = new DescFlexSegments();


                                itemList.Add(itemInfo);
                            }
                            else
                            {
                                using (ISession session = Session.Open())
                                {

                                    itemMaster.Effective.EffectiveDate = DateTime.Parse("2000-01-01 00:00:00");
                                    itemMaster.Effective.DisableDate = DateTime.Parse("9999-12-31 00:00:00");
                                    itemMaster.Effective.IsEffective = true;

                                    itemMaster.Name = item.Name;
                                    itemMaster.SPECS = item.SPECS;
                                    if (!string.IsNullOrEmpty(item.Code1))
                                        itemMaster.Code1 = item.Code1;
                                    if (!string.IsNullOrEmpty(item.Code2))
                                        itemMaster.Code2 = item.Code2;
                                    session.Commit();
                                }
                            }
                        }

                        if (itemList.Count > 0)
                        {
                            proxy.ItemMasterDTOs = itemList;
                            var rt = proxy.Do();

                            string rtnmsg = $"生成成功，一共{rt.Count}个。";
                            if (!string.IsNullOrEmpty(errmsg))
                            {
                                rtnmsg += "失败原因:" + errmsg;
                            }
                            rtn.Code = 1;
                            rtn.Msg = rtnmsg;
                        }

                        //下发
                        foreach (var dtos in xFDTOs.GroupBy(m => m.OrgCode))
                        {
                            //查找下发组织
                            Base.Organization.Organization toOrg = Base.Organization.Organization.Finder.Find($"Code='{dtos.FirstOrDefault().OrgCode}'");
                            //查找集团组织
                            Base.Organization.Organization org = Base.Organization.Organization.Finder.Find("Code='10'");
                            //料品ID集合
                            List<long> IDs = new List<long>();
                            List<string> Codes = new List<string>();

                            foreach (var dto in dtos)
                            {

                                CBO.SCM.Item.ItemMaster itemMaster = CBO.SCM.Item.ItemMaster.Finder.Find($"Code='{dto.ItemCode}' and Org = {org.ID}");
                                if (itemMaster != null)
                                {
                                    CBO.SCM.Item.ItemMaster ckitemMaster = CBO.SCM.Item.ItemMaster.Finder.Find($"Code='{dto.ItemCode}' and Org = {toOrg.ID}");
                                    if (ckitemMaster == null)
                                    {
                                        if (!string.IsNullOrEmpty(dto.ItemCode1))
                                        {
                                            CBO.SCM.Item.ItemMaster itemMaster2 = CBO.SCM.Item.ItemMaster.Finder.Find($"Code1='{dto.ItemCode1}' and Org = {toOrg.ID}");
                                            if (itemMaster2 == null)
                                            {
                                                Codes.Add(itemMaster.Code);
                                                IDs.Add(itemMaster.ID);
                                            }
                                        }
                                        else
                                        {

                                            Codes.Add(itemMaster.Code);
                                            IDs.Add(itemMaster.ID);
                                        }
                                    }


                                }

                            }

                            if (IDs.Count > 0)
                            {
                                try
                                {
                                    OnlineSendObjsProxy xf = new OnlineSendObjsProxy();
                                    xf.FullName = UFIDA.U9.CBO.SCM.Item.ItemMaster.EntityRes.BE_FullName;
                                    xf.IDs = IDs;
                                    xf.FromOrg = org.ID;//Context.LoginOrg.ID;
                                    xf.ToOrgList = new List<long> { toOrg.ID };
                                    var rtns = xf.Do();

                                }
                                catch (System.Exception err)
                                {

                                    foreach (var id in IDs)
                                    {
                                        CBO.SCM.Item.ItemMaster itemMaster = CBO.SCM.Item.ItemMaster.Finder.FindByID(id);

                                        try
                                        {
                                            var idlist = new List<long>();
                                            idlist.Add(id);
                                            OnlineSendObjsProxy xf = new OnlineSendObjsProxy();
                                            xf.FullName = UFIDA.U9.CBO.SCM.Item.ItemMaster.EntityRes.BE_FullName;
                                            xf.IDs = idlist;
                                            xf.FromOrg = org.ID;//Context.LoginOrg.ID;
                                            xf.ToOrgList = new List<long> { toOrg.ID };
                                            xf.Do();

                                        }
                                        catch (System.Exception er)
                                        {
                                            rtn.Code = 0;
                                            rtn.Msg += $";料品{itemMaster.Name}下发{toOrg.Code}组织失败:"+er.Message;

                                        }
                                    }
     	
                                }

                            }


                        }

                        scope.Commit();

                        return rtn;
                    }
                    catch (Exception ex)
                    {
                        scope.Rollback();
                        rtn.Code = 0;
                        rtn.Msg = ex.Message;
                        return rtn;

                    }

                }

            }
        }

    }

    public class XFDTO
    {
        public string OrgCode { get; set; }
        public string ItemCode { get; set; }
        public string ItemCode1 { get; set; }
        public long ItemID { get; set; }
    }
}
